var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var async = require('async');
var ObjectId = require('mongoose').Schema.ObjectId;

var config = require('./config');
var routes = require('./routes/index');
//var users = require('./routes/users');

var app = express();

// view engine setup
app.set('port', process.env.PORT || '3000');
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

var signedCookieParser = cookieParser('chatRoom');
var MongoStore = require('connect-mongo')(session);
var sessionStore = new MongoStore({
  	url: config.mongodb
})

// uncomment after placing your favicon in /public
app.use(favicon(path.join(__dirname, 'static', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, './static')));
app.use(session({
	secret: 'chatRoom',
	resave: true,
	saveUninitialized: false,
	cookie: {
		maxAge: 60 * 1000 * 60
	},
	store: sessionStore
}))

//if ('development' == app.get('env')) {
//app.set('staticPath', '/static')
//} else {
//app.set('staticPath', '/build')
//}
//
//app.use(express.static(__dirname + app.get('staticPath')))

app.use('/', routes);
//app.use('/users', users);

app.use(function(req, res){
	res.sendFile(path.join(__dirname, './static/index.html'));
})
//app.use(function(req, res) {
//  res.sendFile(path.join(__dirname, app.get('staticPath') + '/index.html'))
//})

var server = app.listen(app.get("port"), function(){
	console.log('Express server linsteing on port '+app.get('port'));
})

var Controller = require("./controlls");
var io = require("socket.io").listen(server);

io.set('authorization', function(handshakeData, accept) {
	signedCookieParser(handshakeData, {}, function(err) {
	    if(err){
	      	accept(err, false);
	    }else{
		    sessionStore.get(handshakeData.signedCookies['connect.sid'], function(err, session){
		        if(err){
		          	accept(err.message, false);
		        }else{
			        handshakeData.session = session;
			        if(session._userId){
			              accept(null, true);
			          }else{
			              accept('No login');
			        }
		        }
		    })
	    }
	})
})

var Robot = {
	name: "机器人",
	headUrl: ""
}

io.sockets.on("connection", function(socket){
	//监听用户上线下线
	var _userId = socket.request.session._userId;
	
	Controller.User.online(_userId, function(err, user){
		if(err){
			res.json(500, {msg: err})
		}else{
			if(user._roomId){
				socket.join(user._roomId);
				socket.in(user._roomId).broadcast.emit("joinRoom", {user: user});
				socket.in(user._roomId).broadcast.emit("addMessage", {
					content: user.name + "进入群组",
					creator: Robot,
					createAt: new Date(),
					_id: ObjectId()
				});
			}
		}
	})
	
	socket.on("disconnect", function(){
		Controller.User.offline(_userId, function(err, user){
			if(err){
				res.json(500, {msg: err})
			}else{
				if(user._roomId){
					socket.in(user._roomId).broadcast.emit("leaveRoom", {user: user, room: user._roomId});
					socket.in(user._roomId).broadcast.emit("addMessage", {
						content: user.name + "离开群组",
						creator: Robot,
						createAt: new Date(),
						_id: ObjectId()
					});
					Controller.User.leaveRoom({user: user}, function(){})
				}
			}
		})
	})
	//监听所有的群组
	socket.on("getAllRooms", function(){
		Controller.Rooms.readAllRooms(function(err, data){
			if(err){
				res.json(500, {msg: err})
			}else{
				socket.emit("addAllRooms", data);
			}
		})
	})
	//创建一个新的群组
	socket.on("createNewRoom", function(roomName){
		Controller.Rooms.createNewRoom(roomName, function(err, room){
			if(err){
				res.json(500, {msg: err})
			}else{
				room = room.toObject();
				room.users = [];
				io.sockets.emit("addNewRoom", room);
			}
		})
	})
	//监听获取指定房间的信息
	socket.on("getSpecifyRoom", function(_roomId){
		Controller.Rooms.readSpecifyRoom(_roomId, function(err, data){
			if(err){
				res.json(500, {msg: err})
			}else{
				socket.emit("addSpecifyRoom." + _roomId, data);
			}
		})
	})
	//发送消息
	socket.on("sendMessage", function(data){
		Controller.Message.CreateMsg(data, function(err, data){
			if(err){
				res.json(500, {msg: err})
			}else{
				socket.in(data._roomId).broadcast.emit("addMessage", data);
				socket.emit("addMessage", data);
			}
		})
	})
	//进入房间
	socket.on("joinRoom", function(data){
		Controller.User.joinRoom(data, function(err){
			if(err){
				res.json(500, {msg: err})
			}else{
				socket.join(data.room._id);
				socket.emit("joinRoom." + data.user._id, data);
				socket.in(data.room._id).broadcast.emit("addMessage", {
					content: data.user.name + "进入群组",
					creator: Robot,
					createAt: new Date(),
					_id: ObjectId()
				});
				socket.in(data.room._id).broadcast.emit("joinRoom", data);
			}
		})
	})
	//离开房间
	socket.on("leaveRoom", function(leaver){
		Controller.User.leaveRoom(leaver, function(err){
			if(err){
				res.json(500, {msg: err})
			}else{
				socket.in(leaver.room._id).broadcast.emit("addMessage", {
					content: leaver.user.name + "离开群组",
					creator: Robot,
					createAt: new Date(),
					_id: ObjectId()
				});
				socket.leave(leaver.room._id);
				io.sockets.emit("leaveRoom", leaver);
			}
		})
	})
})

// catch 404 and forward to error handler
app.use(function(req, res, next) {
	var err = new Error('Not Found');
	err.status = 404;
	next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
	app.use(function(err, req, res, next) {
	    res.status(err.status || 500);
	    res.render('error', {
	        message: err.message,
	        error: err
	    });
	});
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});


module.exports = app;
